package com.igeek.web;

import com.igeek.domain.User;
import com.igeek.service.UserService;
import com.igeek.utils.MD5Utils;
import com.igeek.utils.MailUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.DateConverter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.UUID;

/**
 * @author jerryHe
 * @create 2019-10-08 15:59
 */

@WebServlet("/registServlet")
public class RegistServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //BeanUtils转换日期类型
        //1.创建DateConverter 对象
        DateConverter dateConverter = new DateConverter();
        //2.设置可以接收的日期格式
        dateConverter.setPatterns(new String[]{"yyyy-MM-dd","yyyy/MM/dd","yyyy-MM-dd HH:mm:ss"});
        //3.把创建的dataConverter注册到BeanUtils中
        ConvertUtils.register(dateConverter,Date.class);

        //使用beanutils获取页面所有参数
        User user = new User();
        try {
            BeanUtils.populate(user,request.getParameterMap());
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        System.out.println(user);
        //生成uuid
        String uuid = UUID.randomUUID().toString();
        user.setUid(uuid);

        //生成激活码
        String activeCode  = UUID.randomUUID().toString();
        user.setCode(activeCode);

        //调用service
        UserService service = new UserService();
        service.regist(user);
        //*发送内容的格式：超链接，包含随机数
        //http://localhost:8888/webstore/activeServlet?activeCode=XXXX*//*
        String content = "<a href='http://localhost:8888/webstore/activeServlet?activeCode="+activeCode+"'>点击链接激活邮件</a>";
        //发送邮件
        MailUtils.sendMail(user.getEmail(),"激活邮件",content);
        //跳转到页面
        request.getRequestDispatcher("registerSuccess.jsp").forward(request,response);
    }
}
